//
//  DSBuyUnitController.m
//  DSJY
//
//  Created by 冯华强 on 16/9/23.
//  Copyright © 2016年 dsjy. All rights reserved.
//  购买单元

#import "DSBuyUnitController.h"
#import "DSBuyUnitViewModel.h"
#import "DSOrderInfo.h"
#import "DSAccountViewModel.h"
#import "NSString+Extension.h"
#import "DSLoginController.h"
#import "MTNavigationController.h"
#import "UIStoryboard+Extension.h"
#import "DDIAPManager.h"
#import "YQProducts.h"

@interface DSBuyUnitController () <DSLoginControllerDelegate>
//12月长时常
@property (weak, nonatomic) IBOutlet UIButton *longMonthsButton;
//6个月短时常
@property (weak, nonatomic) IBOutlet UIButton *shortMonthsButton;
//购买单元VM
@property (nonatomic, strong) DSBuyUnitViewModel *buyUnitVM;
//订单的参数
@property(nonatomic, strong) DSOrderInfo *orderInfo;
//可购买的商品集合
@property (nonatomic, strong) NSArray *products;
@end

@implementation DSBuyUnitController

#pragma mark - 懒加载
- (DSBuyUnitViewModel *)buyUnitVM
{
    if (_buyUnitVM == nil) {
        _buyUnitVM = [[DSBuyUnitViewModel alloc] init];
    }
    return _buyUnitVM;
}

- (DSOrderInfo *)orderInfo
{
    if (_orderInfo == nil) {
        _orderInfo = [[DSOrderInfo alloc] init];
    }
    return _orderInfo;
}

#pragma mark - 系统回调
- (void)viewDidLoad {
    [super viewDidLoad];
    
    //显示backItem
    [self setupnavigationItem];
    //加载products
//    [self loadProducts];
    //绑定事件
    [self bindEvent];
}

#pragma mark - 设置UI
- (void)loadProducts
{
    //0 需要获得可销售商品(就是我们的APP内购商品的 productsID)
//    NSString * productPath = [[NSBundle mainBundle] pathForResource:@"products.json" ofType:nil];
//    
//    //把JSON 转为 data
//    NSData *jsonData = [NSData dataWithContentsOfFile:productPath];
//    
//    //反序列化
//    self.productArr = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    MTLog(@"%@",self.buyUnitVM.productsList);
    
    //我们需要取出 [{productId:"xxxx"}]  数组里的字典里面的 key 对应的Value值
    //传统写法 ----------------------------------------------
    NSMutableArray *tempArr = [NSMutableArray array];
    
    for (YQProducts *products in self.buyUnitVM.productsList) {
        NSString * valueStr = products.productId;
        
        [tempArr addObject:valueStr];
    }
    
    [SVProgressHUD show];
    //查询产品的信息,查询成功后会返回商品信息
    [[DDIAPManager sharedInstance] requestProducts:tempArr success:^(NSArray *products) {
        [SVProgressHUD dismiss];
        self.products = products;
    } failure:^(NSString *errorMessage, DDIAPManagerFailureType errorType) {
        [SVProgressHUD dismiss];
        NSLog(@"errorMessage:%@--errorType:%ld", errorMessage, (long)errorType);
    }];
}

- (void)setupnavigationItem
{
    self.showBackItem = YES;
}

#pragma mark - 设置事件
- (IBAction)longMonthsButtonClick
{
    [self setupButtonSelected:self.longMonthsButton noSelectedBtn:self.shortMonthsButton];
}

- (IBAction)shortMonthsButtonClick
{
    [self setupButtonSelected:self.shortMonthsButton noSelectedBtn:self.longMonthsButton];
}

- (void)setupButtonSelected:(UIButton *)selectedBtn noSelectedBtn:(UIButton *)noSelectedBtn
{
    if (!selectedBtn.isSelected) {
        selectedBtn.selected = YES;
        noSelectedBtn.selected = NO;
    }
}

//登录
- (void)loginItemClick
{
    DSLoginController *loginVC = (DSLoginController *)[UIStoryboard initialVCWithName:@"DSLoginController"];
    loginVC.title = @"登录";
    loginVC.delegate = self;
    loginVC.showBackItem = YES;
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//立即购买
- (IBAction)buyButtonClick:(UIButton *)btn
{
    if ([NSString isNotEmptyWithStr:[DSAccountViewModel sharedAccount].account.stuId]) {
        self.orderInfo.year = self.longMonthsButton.isSelected ? DSOrderInfoYearLong : DSOrderInfoYearShort;
        self.orderInfo.channel = DSOrderInfoChannelValue;
        for (SKProduct *product in self.products) {
            for (YQProducts *products in self.buyUnitVM.productsList) {
                if ([products.productId isEqualToString:product.productIdentifier] && [products.year isEqualToString:self.orderInfo.year]) {
                    self.orderInfo.product = product;
                    [self.buyUnitVM.requestCommand execute:self.orderInfo];
                    return;
                }
            }
        }
    }else{
        //没有登录、开锁的
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请先登录或注册再购买！谢谢！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *submitAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳转登录控制器
            [self loginItemClick];
        }];
        [alertController addAction:cancelAction];
        [alertController addAction:submitAction];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - 绑定事件
- (void)bindEvent
{
    @weakify(self);
    //初始化
    [self.buyUnitVM.initialBindCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        NSLog(@"%@", [NSThread currentThread]);
        [self loadProducts];
    }];
    
    //如果验证通过，调用命令信号
    [self.buyUnitVM.requestCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        //通知
        [MTNotificationCenter postNotificationName:DSIAPSuccessDidRefreshListNote object:nil];
    }];
    
    //IAP支付成功，刷新列表
    [[[MTNotificationCenter rac_addObserverForName:DSIAPSuccessDidRefreshListNote object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        //执行请求
        [self dismissViewControllerAnimated:YES completion:nil];
    }];
    
    //初始化
    [self.buyUnitVM.initialBindCommand execute:nil];
}

#pragma mark - <DSLoginControllerDelegate>
- (void)loginControllerDidSuccess:(DSLoginController *)vc
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
